/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.uhk.ppro.traveler.dao;

import cz.uhk.ppro.traveler.entity.TUser;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Martin Soušek
 */
@Transactional
public class UsersDao {

    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu");
    private EntityManager em = emf.createEntityManager();

    public List<TUser> getAllUsers() {
        
        return em.createQuery("from TUser").getResultList();
    }
    
    public TUser getUser(int id) {
        
        return em.find(TUser.class, id);
    }
    
    public TUser getUser(String username) {
        
        TUser user;
        try {
            
            user = (TUser) em.createQuery("select u from TUser u where u.username = :uname")
                    .setParameter("uname", username)
                    .getSingleResult();
            
            return user;
        }
        
        catch (Exception e) {
            
            return null;
        }
    }
    
    public void addUser(TUser u) {
        
        em.getTransaction().begin();
        em.persist(u);
        em.getTransaction().commit();
    }
}
